using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.Util;

namespace Moogle
{
    /// <summary>
    /// Learn Activity class.  This activity provides the user with drug interaction information regarding their prescriptions
    /// when they are mixed with over the counter (OTC) medication. It's target consumer is the Program class.
    /// </summary>
    [Activity(Label = "Learn", MainLauncher = false, Icon = "@drawable/icon", Theme = "@android:style/Theme.Holo.Light", NoHistory = true)]
    [IntentFilter (new[]{Intent.ActionMain})]
    public class ActivityLearn : ListActivity
    {
        #region Local Memory
        
        /// <summary>
        /// Constant using to identify (filter) entries created in the
        /// Android Log by this class.
        /// </summary>
        private const string __C_TAG = "ActivityLearn";
        /// <summary>
        /// Constant string value defining the filename in which all
        /// possible medications are stored.  This file has 
        /// a CSV format--
        /// [TYPE],[MEDICATION NAME]
        /// </summary>
        private const string __C_MEDICATIONS_FILENAME = "medications.csv";
        /// <summary>
        /// Constant string value defining the filename where the user's
        /// medication information is stored.  This file has 
        /// a CSV format--
        /// [TYPE],[MEDICATION NAME]
        /// </summary>
        private const string __C_PRESCRIBED_MEDICATIONS_FILENAME = "prescribed_medications.csv";
  
        #endregion
        #region OnCreate Control Function
    
        /// <summary>
        /// Class (or Activity) entry point.
        /// </summary>
        /// <param name="bundle">Android.OS.Bundle object instance that can be used to pass data to activity at startup.</param>
        protected override void OnCreate(Bundle bundle)
        {

            Log.Info(__C_TAG, "OnCreate started.");

            try
            {
                base.OnCreate(bundle);
                this.SetContentView(Resource.Layout.learn);

                /// Configure the Show Button Event Delegate
                #region ...
                Button _buttonShow = FindViewById<Button>(Resource.Id.doShow);
                _buttonShow.Click += delegate
                {
                    var _IntentShow = new Intent(this, typeof(ActivityOTCUpdate));
                    StartActivity(_IntentShow);
                };
                #endregion

                /// Configure the Back Button Delegate
                #region ...
                Button _buttonBack = FindViewById<Button>(Resource.Id.doBack);
                _buttonBack.Click += delegate
                {
                    var _IntentShow = new Intent(this, typeof(Program));
                    StartActivity(_IntentShow);
                };
                #endregion
                String _strRxSelections = "Rx: ";
                String _strOTCSelections = "OTC: ";
                List<String> _listRxSelections = new List<String>();
                List<String> _listOTCSelections = new List<String>();
                String[] _strArrPrescribedMeds = new String[2];

                /// Test Whether the PrescribedMedication database
                /// table contains any data.  If it does, then use
                /// the data stored in th table.  Otherwise,
                /// use the contents of the "prescribed_medications_csv"
                /// to populate the RX/OTC Medication lists
                #region ...

                dbCommands _clsDbCommands = new dbCommands(this);
                IList<Medication> _colAllMedcations = _clsDbCommands.GetAllPrescribedMedication();
                
                if (null==_colAllMedcations || _colAllMedcations.Count == 0)
                {
                    Log.Debug(__C_TAG, "Database is empty.");

                    string _path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
                    Log.Debug(__C_TAG, _path);
                    string _filename = Path.Combine(_path, __C_PRESCRIBED_MEDICATIONS_FILENAME);

                    if (File.Exists(_filename))
                    {
                        /// Populate the OTC/Rx Lists using the
                        /// contents of the file
                        #region ...

                        String[] _strArrDelimiters = { "," };

                        using (var _f = new StreamReader(OpenFileInput(__C_PRESCRIBED_MEDICATIONS_FILENAME)))
                        {
                            string _line;
                            do
                            {
                                _line = _f.ReadLine();

                                String[] _strValues = _line.Split(_strArrDelimiters, StringSplitOptions.RemoveEmptyEntries);

                                if (null != _strValues && _strValues.Length == 2)
                                {
                                    switch (_strValues[0].Trim().ToUpper())
                                    {
                                        case "RX":
                                            _listRxSelections.Add(_strValues[1]);
                                            break;
                                        case "OTC":
                                            _listOTCSelections.Add(_strValues[1]);
                                            break;

                                    } // end switch

                                } // end if
                            } while (!_f.EndOfStream);
                        } // end using

                        #endregion

                    } // end if
                } // end if
                /// Otherwise use database table...
                else
                {
                    foreach (Medication _med in _colAllMedcations)
                    {
                        switch (_med.Type.Trim().ToUpper())
                        {
                            case "RX":
                                _listRxSelections.Add(_med.Name.Trim());
                                break;
                            case "OTC":
                                _listOTCSelections.Add(_med.Name.Trim());
                                break;
                        } // end switch
                    } // end foreach
                } // end else

                #endregion

                /// Use the List Objects build two strings-- (1) summarizing
                /// Rx medication and (2) summarizing OTC medication.
                #region ...

                int _intItemIndex = 1;

                if (_listRxSelections.Count > 0)
                {
                    foreach (string _rx in _listRxSelections)
                    {
                        _strRxSelections += _rx;
                        if (_intItemIndex < _listRxSelections.Count)
                            _strRxSelections += ", ";
                        _intItemIndex++;
                    } // end foreach
                } // end if
                else
                    _strRxSelections += "N/A";

                _intItemIndex = 1;

                if (_listOTCSelections.Count > 0)
                {
                    foreach (string _otc in _listOTCSelections)
                    {
                        _strOTCSelections += _otc;
                        if (_intItemIndex < _listOTCSelections.Count)
                            _strOTCSelections += ", ";
                        _intItemIndex++;
                    } // end foreach
                } // end if
                else
                    _strOTCSelections += "N/A";

                #endregion

                /// Add the two strings into a new string array and use
                /// it to populate the list adapter at the top of the 
                /// screen.
                #region ...

                _strArrPrescribedMeds[0] = _strRxSelections;
                _strArrPrescribedMeds[1] = _strOTCSelections;

                this.ListAdapter = new ArrayAdapter<String>(this, Resource.Layout.list_item_textview, _strArrPrescribedMeds);

                #endregion

            } // end try
            catch (SystemException err)
            {
                Log.Error(__C_TAG, err.Message);
            } // end catch
            finally
            {
                Log.Info(__C_TAG, "OnCreate ended.");
            } // end finally
        }
       
        #endregion
    }
}